package com.liao.badminton.handler.security;


import com.liao.badminton.code.RespCodeMessage;
import com.liao.badminton.code.ResponseRest;
import com.liao.badminton.code.util.ResponseUtils;
import com.liao.badminton.context.BaseContextHandler;
import com.liao.badminton.redis.RedisEnum;
import com.liao.badminton.redis.RedisUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) {
        ResponseRest result;
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            result = ResponseRest.fail("login", RespCodeMessage.SECURITY_LOGIN_ERROR, e.getMessage());
        } else if (e instanceof LockedException) {
            result = ResponseRest.fail("login", RespCodeMessage.SECURITY_ACCOUNT_LOCK);
        } else if (e instanceof CredentialsExpiredException) {
            result = ResponseRest.fail("login", RespCodeMessage.SECURITY_CREDENTIAL_EXPIRE);
        } else if (e instanceof AccountExpiredException) {
            result = ResponseRest.fail("login", RespCodeMessage.SECURITY_ACCOUNT_EXPIRE);
        } else if (e instanceof DisabledException) {
            result = ResponseRest.fail("login", RespCodeMessage.SECURITY_ACCOUNT_FORBIDDEN);
        } else {
            result = ResponseRest.fail("login");
        }
        RedisUtil.toDelete(RedisEnum.badminton_user_info_name, BaseContextHandler.getUserName());
        ResponseUtils.out(response, result);
    }
}
